import { createAsyncThunk, createSlice, PayloadAction } from "@reduxjs/toolkit";
import axios from "axios";

interface storeTs {
  key: number;
  name: string;
  khzt: string;
  khxj: string;
  lxr: string;
  phone: string;
  time: string;
  timefalse: string;
}
interface postsTs {
  key: number;
  name: string;
  Customer: string;
  stage: string;
  bjnum: string;
  price: string;
  time: string;
  days: boolean;
}
interface initialStateTS {
  data: Array<storeTs>;
  posts: Array<postsTs>;
}
let initialState: initialStateTS = {
  data: [],
  posts: [],
};

const todosSlice = createSlice({
  name: "todos",
  initialState,
  reducers: {
    // 搜索数据
    search_data(state: initialStateTS, action) {
      state.data = action.payload;
    },
    // 获取数据
    shop_data(state: initialStateTS, action) {
      state.data = action.payload;
    },
    //添加商品列表
    add_data(state: initialStateTS, action) {
      state.data.push(action.payload);
    },
    //编辑商品列表
    edit_data(state: initialStateTS, action) {
      let index = state.data.findIndex((item) => {
        return item.key == action.payload.key;
      });
      state.data[index] = action.payload;
    },
    //删除商品列表
    del_data(state: initialStateTS, action) {
      state.data = state.data.filter((item) => {
        return item.key !== action.payload;
      });
    },
    // 搜索数据
    search_posts(state: initialStateTS, action) {
      state.posts = action.payload;
    },
    // 获取数据
    shop_posts(state: initialStateTS, action) {
      state.posts = action.payload;
    },
    //添加商品列表
    add_posts(state: initialStateTS, action) {
      state.posts.push(action.payload);
    },
    //编辑商品列表
    edit_posts(state: initialStateTS, action) {
      let index = state.posts.findIndex((item) => {
        return item.key == action.payload.key;
      });
      state.data[index] = action.payload;
    },
    //删除商品列表
    del_posts(state: initialStateTS, action) {
      state.posts = state.posts.filter((item) => {
        return item.key !== action.payload;
      });
    },
  },
});

export const comFn = todosSlice.actions;
export default todosSlice.reducer;
export let get_data = createAsyncThunk("get_data", async (_, store) => {
  let res = await axios.get("http://localhost:3000/data");
  console.log(res.data);

  return res.data;
});

export let get_posts = createAsyncThunk("get_posts", async (_, store) => {
  let res = await axios.get("http://localhost:3000/posts");
  console.log(res.posts);

  return res.posts;
});
